package com.probiz.estoresa.catalog.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.Constants;
import com.probiz.estore.catalog.model.ContentCategoryFullyModel;
import com.probiz.estore.catalog.service.ContentCategoryManager;
import com.probiz.estore.common.model.catalog.ContentCategory;
import com.probiz.estore.common.model.content.Content;
import com.probiz.estore.common.model.content.ContentRelatedType;
import com.probiz.estore.content.model.ContentRelatedTypeSearchCriteria;
import com.probiz.estore.content.service.AutoEvalRelatedContentManager;
import com.probiz.estore.content.service.ContentRelatedTypeManager;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.webapp.util.RequestUtil;

public class ContentCategoryController extends GenericStoreAdminController<ContentCategory> {
    private ContentCategoryManager contentCategoryManager = null;
    private ContentRelatedTypeManager contentRelatedTypeManager = null;
    private AutoEvalRelatedContentManager autoEvalRelatedContentManager = null;

    public void setContentCategoryManager(ContentCategoryManager inMgr) {
        this.contentCategoryManager = inMgr;
    }

    public void setContentRelatedTypeManager(
			ContentRelatedTypeManager contentRelatedTypeManager) {
		this.contentRelatedTypeManager = contentRelatedTypeManager;
	}
    

	public void setAutoEvalRelatedContentManager(
			AutoEvalRelatedContentManager autoEvalRelatedContentManager) {
		this.autoEvalRelatedContentManager = autoEvalRelatedContentManager;
	}

	protected String getEntityName(ContentCategory entity) {
        return entity.getContentCategoryName();
    }

    

    protected void initController() throws Exception {
        mgr = contentCategoryManager;
    }

    public ModelAndView defaultAction(HttpServletRequest request,
                                      HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("catalog/contentCategoryList");

        ContentCategory treeRoot = contentCategoryManager.getById(1);
        Set<ContentCategory> categorySet=treeRoot.getChildren();
        List<ContentCategory> categoryList=new ArrayList<ContentCategory>();
        categoryList.addAll(categorySet);    
        mv.addObject("categoryList", categoryList);
        mv.addObject("treeRoot", treeRoot);
        return mv;
    }
    
    /**
	 * 获取树节点，ajax方式
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView getTreeItems(HttpServletRequest request,HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("catalog/include/contentCategoryTreeAjax");
		String categoryId = RequestUtil.getParameterNullSafe(request, "categoryId");
		ContentCategory parent = contentCategoryManager.getById(Integer.valueOf(categoryId));
		Set<ContentCategory> categorySet = parent.getChildren();
		List<ContentCategory> categoryList = new ArrayList<ContentCategory>();
		categoryList.addAll(categorySet);
		mv.addObject("categoryList",categoryList);
		return mv;
		
	}    

    public ModelAndView edit(HttpServletRequest request,
                             HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("catalog/contentCategoryForm");

        Integer categoryId = RequestUtil.getInteger(request, "categoryId");
        if (null != categoryId) {
            //case:编辑
            ContentCategory category = contentCategoryManager
                    .getById(categoryId);
            mv.addObject("category", category);
        } else {
            //case:新增
            Integer parentCategoryId = RequestUtil.getInteger(request,
                    "parentCategoryId");
            ContentCategory parentCategory = contentCategoryManager
                    .getById(parentCategoryId);
            mv.addObject("parentCategory", parentCategory);
            ContentCategory category = new ContentCategory();
            Short categoryType = Short.valueOf(RequestUtil.getParameterNullSafe(request, "categoryType"));
            category.setParent(parentCategory);
            category.setCategoryType(categoryType);
            mv.addObject("category", category);
        }
        
      //start:激活的关联推荐类型
		ContentRelatedTypeSearchCriteria contentRelatedTypeSearchCriteria = new ContentRelatedTypeSearchCriteria();
		contentRelatedTypeSearchCriteria.setStatus(Constants.FLAG_TRUE);
		contentRelatedTypeSearchCriteria.setIsApplyToCategory(Constants.FLAG_TRUE);
		List<ContentRelatedType> relatedTypeList = contentRelatedTypeManager.getContentRelatedTypeBySearchCriteria(contentRelatedTypeSearchCriteria);
		mv.addObject("relatedTypeList", relatedTypeList);
		//end:激活的关联推荐类型
        return mv;
    }

    public ModelAndView add(HttpServletRequest request,
                            HttpServletResponse response) {
        return edit(request, response);
    }

    public ModelAndView selectType(HttpServletRequest request,
                                   HttpServletResponse response) {
        return new ModelAndView("catalog/contentCategoryFormSelectType");
    }

    /**
     * 按categoryIds的顺序更新目录sortOrder
     *
     * @param request  request
     * @param response response
     * @return modelAndView
     */
    public ModelAndView updateCategoriesSortOrder(HttpServletRequest request,
                                                  HttpServletResponse response) {
        Integer[] categoryIds = RequestUtil.getIntegerArrayNullSafe(request,
                "categoryIds");
        // MethodUtils.invokeMethod(mgr, "updateCategoriesSortOrder", new
        // Object[]{categoryIds});
        contentCategoryManager.updateCategoriesSortOrder(categoryIds);
        return null;
    }

    /**
     * 前置绑定，避免验证错误
     *
     * @param entity 实体
     */
    private void bindReady(ContentCategory entity) {
        if (null == entity.getCategoryId()) {
            //case:新增
            entity.setStatus(ContentCategory.STATUS_ACTIVE);
            entity.setSortOrder(ContentCategory.SORTORDER_DEFAULT_VALUE);
        }
    }

    /*
     * 保存前的检验和赋值.保存目录判断目录Code是否重复
     */
	protected void preSave(HttpServletRequest request, ContentCategory entity, BindException errors) {
		// start:赋值dispalyFlag
		String[] displayFlagArray = RequestUtil.getParameterValuesNullSafe(request, "displayFlag");
		StringBuffer displayFlag = new StringBuffer();
		for (String flag : displayFlagArray) {
			displayFlag.append(flag);
		}
		entity.setDisplayFlag(displayFlag.toString());
		// end:赋值dispalyFlag

	}
     
    public ModelAndView save(HttpServletRequest request,
                             HttpServletResponse response) throws Exception {

        // 取得Form对应的Model
        ContentCategory entity = formBackingObject(request);
        BindException errors = null;
        Map<String, Object> data = new HashMap<String, Object>();
        try {
            bindReady(entity);
            ServletRequestDataBinder binder = bindAndValidate(request, entity);
            //noinspection ThrowableInstanceNeverThrown
            errors = new BindException(binder.getBindingResult());
            // 传给子类的实现，后者可以继续验证和加入错误到errors
            preSave(request, entity, errors);
            if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
            	Map<String, Object> saveData = contentCategoryManager.saveFully(getContentCategoryFullyModel(request,entity,data));
            	data.putAll(saveData);
            }
        } catch (ApplicationException e) {
            handleApplicationException(errors, e);
        }
        buildReturnInfo(data, entity, request);

        return getModelAndAjaxJsonView(data);
    }

    //构造模型，方便保存
	private ContentCategoryFullyModel getContentCategoryFullyModel(HttpServletRequest request,	ContentCategory contentCategory, Map<String, Object> data) {
		ContentCategoryFullyModel model = new ContentCategoryFullyModel();
	
		model.setContentCategory(contentCategory);
		// --------- start: 绑定推荐关联文章----------------
		String[] relatedTypeIds = RequestUtil.getParameterValuesNullSafe(request, "relatedTypeIds");
		String[] relatedContentIds = RequestUtil.getParameterValuesNullSafe(request, "relatedContentIds");
		model.setRelatedTypeIds(relatedTypeIds);
		model.setRelatedContentIds(relatedContentIds);
		// --------- end: 绑定推荐关联文章----------------
		
		return model;
	}
    /**
     * 按categoryId删除目录
     */
    public ModelAndView delete(HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
        Integer categoryId = RequestUtil.getInteger(request, "categoryId");
        ContentCategory contentCategory = contentCategoryManager.getById(categoryId);
		Map<String, Object> data = contentCategoryManager.deleteFully(contentCategory);
		return getModelAndAjaxJsonView(data);
    }
    

	/**
	 * 加入返回参数
	 * 
	 * @param data
	 * @param product
	 * @param request
	 */
	private void buildReturnInfo(Map<String, Object> data,
			ContentCategory entity, HttpServletRequest request) {
        data.put("categoryId", entity.getCategoryId());
        data.put("categoryCode", entity.getCategoryCode());
        data.put("categoryType", entity.getCategoryType());
        data.put("categoryName", entity.getCategoryName());
        data.put("depth", entity.getDepth());
        data.put("itemCount", entity.getItemCount());
        data.put("activeItemCount", entity.getActiveItemCount());

	}
	
	/**
	 * 获得自动评估文章列表
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView getAutoEvalContents(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		Map<String, Object> data = new HashMap<String, Object>();
		Integer contentCategoryId = RequestUtil.getInteger(request, "contentCategoryId");
		Integer relatedTypeId = RequestUtil.getInteger(request, "relatedTypeId");
		ContentRelatedType contentRelatedType = contentRelatedTypeManager.getById(relatedTypeId);
		List<Content> result = autoEvalRelatedContentManager.getContentsByRuleCodeBySourceId(contentRelatedType.getRuleCode(), contentCategoryId, 0, 5);
		JSONArray autoEvalContentArray = new JSONArray();
		for(Content content: result){
			JSONObject jsonContent = new JSONObject();
			jsonContent.put("id", content.getContentId());
			jsonContent.put("contentTitle", content.getContentTitle());
			jsonContent.put("imageUrl", content.getImageUrl());
			autoEvalContentArray.add(jsonContent);
		}
		data.put("autoEvalContentArray", autoEvalContentArray);
		data.put("relatedTypeId", relatedTypeId);
		return getModelAndAjaxJsonView(data);
	}

   
}
